<template>
  <div class="app-container">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && pageLoading" 
      :showHeader="true"
      :showCards="false"
      :showTable="true"
      :tableColumns="3"
      :tableRows="5"
      :showPagination="false"
    />
    
    <el-row :gutter="24" v-else>
      <el-col :span="24">
        <el-card style="margin-bottom: 10px">
          距离考试结束还有：
          <exam-timer v-model="paperData.time_limit" @timeout="doHandler()" />
          <el-button style="float: right; margin-top: -10px" type="primary" icon="el-icon-plus" :loading="loading"
            @click="handHandExam()">
            {{ handleText }}
          </el-button>
        </el-card>
      </el-col>

      <el-col :span="6" :xs="24" style="margin-bottom: 10px">
        <el-card>
          <p class="card-title">答题卡</p>
          <el-row :gutter="24" class="card-line" style="padding-left: 10px">
            <el-tag type="info">未作答</el-tag>
            <el-tag type="success">已作答</el-tag>
            <el-tag type="warning">正在作答</el-tag>
          </el-row>

          <div v-if="paperData.radioList !== undefined && paperData.radioList.length > 0">
            <p class="card-title">单选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.radioList" :key="item.id" :type="cardItemClass(item.is_answered, item.id)"
                @click="handSave(item)">
                {{ item.sort + 1 }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.multiList !== undefined && paperData.multiList.length > 0">
            <p class="card-title">多选题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.multiList" :key="item.id" :type="cardItemClass(item.is_answered, item.id)"
                @click="handSave(item)">{{ item.sort + 1 }}</el-tag>
            </el-row>
          </div>

          <div v-if="paperData.judgeList !== undefined && paperData.judgeList.length > 0">
            <p class="card-title">判断题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.judgeList" :type="cardItemClass(item.is_answered, item.id)" :key="item.id"
                @click="handSave(item)">{{ item.sort + 1 }}</el-tag>
            </el-row>
          </div>
          <div v-if="paperData.questionList !== undefined && paperData.questionList.length > 0
            ">
            <p class="card-title">问答题</p>
            <el-row :gutter="24" class="card-line">
              <el-tag v-for="item in paperData.questionList" :key="item.id"
                :type="cardItemClass(item.is_answered, item.id)" @click="handSave(item)">{{ item.sort + 1 }}</el-tag>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <el-col :span="18" :xs="24">
        <el-card class="qu-content">
          <p v-html="quData.sort + 1 + '.' + quData.stem + stem[quData.type]" v-if="quData.stem" style="
                                      display: inline-flex;
                                      justify-content: start;
                                      flex-wrap: nowrap;
                                      align-items: center;
                                    " />
          <!-- 单选题 -->
          <div v-if="quData.type == 1">
            <el-radio-group v-model="radioValue">
              <el-radio v-for="item in quData.option" :label="item.id" :key="item.id">{{ item.name }}.{{ item.content }}
                <div v-if="item.image != null && item.image != ''" style="clear: both">
                  <el-image :src="item.image" style="max-width: 100%" />
                </div>
              </el-radio>
            </el-radio-group>
          </div>
          <!-- 多选题 -->
          <div v-if="quData.type == 2">
            <el-checkbox-group v-model="multiValue">
              <el-checkbox v-for="item in quData.option" :label="item.id" :key="item.id">{{ item.name }}.{{ item.content
              }}
                <div v-if="item.image != null && item.image != ''" style="clear: both">
                  <el-image :src="item.image" style="max-width: 100%" />
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <!-- 判断题 -->
          <div v-if="quData.type == 3">
            <el-radio-group v-model="radioValue">
              <el-radio :label="1">对 </el-radio>
              <el-radio :label="0">错 </el-radio>
            </el-radio-group>
          </div>
          <!-- 问答题 -->
          <div v-if="quData.type == 4">
            <el-input type="textarea" v-model="questionValue" placeholder="请填写答案"></el-input>
          </div>
        </el-card>

        <div style="margin-top: 20px">
          <el-button v-if="showPrevious" type="primary" icon="el-icon-back" @click="handPrevious()">
            上一题
          </el-button>

          <el-button v-if="showNext" type="warning" icon="el-icon-right" @click="handNext()">
            下一题
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  paperDetail,
  fillAnswer,
  handExam,
  answerUpdate,
  answerDetail,
} from "@/api/vadmin/exam/exam";
// import { quDetail, handExam, fillAnswer } from "@/api/vadmin/paper/exam";
import { Loading } from "element-ui";
import ExamTimer from "@/views/vadmin/exam/components/ExamTimer";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "ExamProcess",
  components: { ExamTimer, MobileSkeleton },

  data() {
    return {
      // 全屏/不全屏
      isFullscreen: false,
      showPrevious: false,
      showNext: true,
      loading: false,
      pageLoading: true,
      isMobile: false,
      mediaQueryList: null,
      is_modify: "", //是否可以修改
      handleText: "交卷",
      // 试卷ID
      paperId: "",
      // 当前答题卡
      cardItem: {},
      cardAnswer: null,
      allItem: [],
      // 当前题目内容
      quData: {
        answerList: [],
      },
      // 试卷信息
      paperData: {
        time_limit: 99999,
        radioList: [],
        multiList: [],
        judgeList: [],
        questionList: [],
      },
      stem: { 1: "(单选题)", 2: "(多选题)", 3: "(判断题)", 4: "(问答题)" },
      // 单选选定值
      radioValue: null,
      // 多选选定值
      multiValue: [],
      //问答题
      questionValue: "",
      // 已答ID
      answeredIds: [],
    };
  },

  watch: {
    radioValue(newVal, oldVal) {
      this.loading = true;
      this.$nextTick(() => {
        // console.log("获取新的答案", newVal);
        //判断最新数据是否为数组
        if (Object.prototype.toString.call(newVal) === "[object Array]") {
          this.radioValue = newVal[0];
          this.loading = false;
        } else {
          this.radioValue = newVal;
          this.loading = false;
        }
      });
    },
    multiValue(newVal, oldVal) {
      this.loading = true;
      this.$nextTick(() => {
        this.multiValue = newVal;
        this.loading = false;
      });
    },
    questionValue(newVal, oldVal) {
      this.loading = true;
      this.$nextTick(() => {
        this.questionValue = newVal;
        this.loading = false;
      });
    },
    cardAnswer(newVal, oldVal) {
      this.loading = true;
      this.$nextTick(() => {
        this.cardAnswer = newVal;
        this.loading = false;
      });
    },
  },

  created() {
    const id = this.$route.params.id;
    if (typeof id !== "undefined") {
      this.paperId = id;
      this.fetchData(id);
    }
  },

  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    // 初始化试卷
    fetchData(id) {
      paperDetail(id).then((response) => {
        // console.log(888, response)
        if ((response.code = 200)) {
          // 试卷内容
          // console.log("试卷----", response);

          //存储试卷是否可修改
          this.is_modify = response.is_modify;

          /*考试倒计时start*/
          var date1 = response.start_time; //开始考试时间
          var date2 = new Date(); //当前
          this.paperData.time_limit =
            response.time_limit * 60 -
            (date2.getTime() - new Date(date1).getTime()) / 1000; //时间差的毫秒数
          /*考试倒计时end*/
          // console.log(111, this.paperData.time_limit)



          // 题目分类
          this.paperData.radioList = response.question.filter((item) => {
            return item.type == "1";
          });
          this.paperData.multiList = response.question.filter((item) => {
            return item.type == "2";
          });
          this.paperData.judgeList = response.question.filter((item) => {
            return item.type == "3";
          });
          this.paperData.questionList = response.question.filter((item) => {
            return item.type == "4";
          });

          //所有题目添加编号
          this.allItem = response.question.map((item, i) => {
            item.sort = i;
            return item;
          });

          // 获得第一题内容
          this.cardItem = this.allItem[0];
          if (this.cardItem.type == "1" && this.cardItem.is_answered == true) {
            this.radioValue = this.cardItem.value;
          } else if (this.cardItem.type == "2" && this.cardItem.is_answered == true) {
            this.multiValue = this.cardItem.answer.value;
          } else if (this.cardItem.type == "3" && this.cardItem.is_answered == true) {
            this.radioValue = this.cardItem.answer.value[0];
          } else if (this.cardItem.type == "4" && this.cardItem.is_answered == true) {
            this.questionValue = this.cardItem.value[0];
          }

          // 当前选定
          this.fetchQuData(this.cardItem);
          this.pageLoading = false;
        } else if (response.code == 201) {
          this.$confirm("response.msg", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            that.$router.push({
              name: "Exam",
            });
          });
        }
      }).catch(err => {
        this.$confirm("本场考试已超时，未完成试卷已自动提交，确定后返回考试列表", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).then(() => {
          this.$router.push({
            name: "Exam",
          });
        });
      })
    },
    // 答题卡样式
    cardItemClass(answered, quId) {
      if (quId === this.cardItem.id) {
        return "warning";
      }

      if (answered) {
        return "success";
      }

      if (!answered) {
        return "info";
      }
    },

    /**
     * 统计有多少题没答的
     * @returns {number}
     */
    countNotAnswered() {
      let notAnswered = 0;

      this.paperData.radioList.forEach(function (item) {
        if (!item.is_answered) {
          notAnswered += 1;
        }
      });

      this.paperData.multiList.forEach(function (item) {
        if (!item.is_answered) {
          notAnswered += 1;
        }
      });

      this.paperData.judgeList.forEach(function (item) {
        if (!item.is_answered) {
          notAnswered += 1;
        }
      });
      this.paperData.questionList.forEach(function (item) {
        if (!item.is_answered) {
          notAnswered += 1;
        }
      });

      return notAnswered;
    },

    /**
     * 下一题
     */
    handNext() {
      const index = this.cardItem.sort + 1;
      // console.log(`第${index}题`);
      this.handSave(this.allItem[index]);
    },

    /**
     * 上一题
     */
    handPrevious() {
      const index = this.cardItem.sort - 1;
      // console.log(`第${index}题`);
      this.handSave(this.allItem[index]);
    },

    doHandler() {
      this.handleText = "正在交卷，请等待...";
      this.loading = true;
      handExam(this.paperId, { is_submited: true }).then((res) => {
        // console.log("交卷2", res);
        this.$message({
          message: "试卷提交成功，即将进入试卷详情！",
          type: "success",
        });

        this.$router.push({ name: "Showexam", params: { id: this.paperId } });
      });
    },

    // 交卷操作
    handHandExam() {
      const that = this;
      // console.log("审卷", this.allItem);
      // 交卷保存答案
      this.handSave(this.cardItem, function () {
        const notAnswered = that.countNotAnswered();
        let msg = "确认要交卷吗？";
        if (notAnswered > 0) {
          // console.log("还有题目没回答");
          msg = "您还有" + notAnswered + "题未作答，确认要交卷吗?";
        }

        that
          .$confirm(msg, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            that.doHandler();
          })
          .catch(() => {
            that.$message({
              type: "info",
              message: "交卷已取消，您可以继续作答！",
            });
          });
      });
    },

    // 保存答案
    handSave(item, callback) {
      // console.log("保存答案", "下一题--", item);
      let type_name = "";
      this.cardAnswer = null;
      if (this.cardItem.type == "1") {
        this.cardAnswer = this.radioValue;

        type_name = "SingleChoiceAnswer";
      } else if (this.cardItem.type == "2") {
        type_name = "MultiChoiceAnswer";
        this.cardAnswer = this.multiValue;
      } else if (this.cardItem.type == "3") {
        type_name = "TrueFalseAnswer";
        // console.log("判断题档案", this.radioValue);
        this.cardAnswer = this.radioValue;
      } else if (this.cardItem.type == "4") {
        type_name = "TextAnswer";
        this.cardAnswer = this.questionValue;
      }

      const params = {
        paper: this.paperId,
        question: this.cardItem.id,
        value: this.cardAnswer,
      };
      // console.log("答案", params, this.cardItem);

      // 判断是否已作答
      if (this.cardItem.is_answered) {
        // console.log("已作答");
        // 判断是否可修改
        if (this.is_modify) {
          answerDetail(type_name, this.cardItem.id, this.paperId).then((res) => {
            // console.log("获取服务器上次答题结果", res);
            answerUpdate(params, type_name, res[0].id).then((i) => {
              // console.log("已修改----", this.allItem, this.cardItem);
              this.allItem[this.cardItem["sort"]].answer.value = this.cardAnswer;
              /* 按钮判断-----------strat*/
              if (item.id == this.allItem[0].id) {
                this.showPrevious = false;
              } else {
                this.showPrevious = true;
              }

              // 最后一个索引
              const last = this.allItem.length - 1;

              if (item.id == this.allItem[last].id) {
                this.showNext = false;
              } else {
                this.showNext = true;
              }
              /* 按钮判断-----------end*/

              // 最后一个动作，交卷
              if (callback) {
                callback();
              }

              this.fetchQuData(item); // 查找详情
            });
          });
        } else {
          // console.log(8080);
          /* 按钮判断-----------strat*/
          if (item.id == this.allItem[0].id) {
            this.showPrevious = false;
          } else {
            this.showPrevious = true;
          }

          // 最后一个索引
          const last = this.allItem.length - 1;

          if (item.id == this.allItem[last].id) {
            this.showNext = false;
          } else {
            this.showNext = true;
          }
          /* 按钮判断-----------end*/

          // 最后一个动作，交卷
          if (callback) {
            callback();
          }
          this.fetchQuData(item); // 查找详情
        }
      } else {
        if (params.value == null || params.value.length == 0) {
          // console.log(77, "没有答案", params.value);
          this.$alert("请先提交本题答案", {
            confirmButtonText: "确定",
            callback: (action) => { },
          });
        } else {
          // console.log(77, "有", params.value);
          /* 按钮判断-----------strat*/
          if (item.id == this.allItem[0].id) {
            this.showPrevious = false;
          } else {
            this.showPrevious = true;
          }
          // 最后一个索引
          const last = this.allItem.length - 1;

          if (item.id == this.allItem[last].id) {
            this.showNext = false;
          } else {
            this.showNext = true;
          }
          /* 按钮判断-----------end*/

          //提交答案并设置为已作答
          fillAnswer(params, type_name).then((res) => {
            // console.log("提交答案后", res);
            // 必须选择一个值
            if (this.cardAnswer.length > 0 || typeof this.cardAnswer === "number") {
              // 加入已答列表
              this.cardItem.is_answered = true;
              this.allItem[this.cardItem["sort"]].answer.value = this.cardAnswer;
            }

            // 最后一个动作，交卷
            if (callback) {
              callback();
            }

            // 查找详情
            this.fetchQuData(item);
          });
        }
      }
    },

    // 试卷详情
    fetchQuData(item) {
      // 打开
      const loading = Loading.service({
        text: "拼命加载中",
        background: "rgba(0, 0, 0, 0.7)",
      });

      // 获得详情
      this.cardItem = item;
      this.quData = item;
      // console.log(1111, item);
      if (item.is_answered) {
        if (item.type == 1) {
          this.multiValue = [];
          this.questionValue = "";
          this.radioValue = item.answer.value;
        } else if (item.type == 2) {
          this.radioValue = "";
          this.questionValue = "";
          this.multiValue = item.answer.value;
        } else if (item.type == 3) {
          this.multiValue = [];
          this.questionValue = "";
          this.radioValue = item.answer.value;
        } else if (item.type == 4) {
          this.radioValue = "";
          this.multiValue = [];
          this.questionValue = item.answer.value;
        }
      } else {
        // console.log("当前题目", item);
        this.radioValue = null;
        this.multiValue = [];
        this.questionValue = "";
      }

      // 填充该题目的答案
      this.quData.option.forEach((item) => {
        if ((this.quData.type === 1 || this.quData.type === 3) && item.answered) {
          this.radioValue = item.id;
        }
        if (this.quData.type === 2 && item.answered) {
          this.multiValue.push(item.id);
        }
      });

      // 关闭详情
      loading.close();
    },
  },
};
</script>

<style scoped>
.qu-content div {
  line-height: 30px;
}

.el-checkbox-group label,
.el-radio-group label {
  width: 100%;
}

.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}

.card-line {
  padding-left: 10px;
}

.card-line span {
  cursor: pointer;
  margin: 2px;
}

::v-deep .el-radio,
.el-checkbox {
  padding: 9px 20px 9px 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}

.is-checked {
  border: #409eff 1px solid;
}

.el-radio img,
.el-checkbox img {
  max-width: 200px;
  max-height: 200px;
  border: #dcdfe6 1px dotted;
}

::v-deep .el-checkbox__inner {
  display: none;
}

::v-deep .el-radio__inner {
  display: none;
}

::v-deep .el-checkbox__label {
  line-height: 30px;
}

::v-deep .el-radio__label {
  line-height: 30px;
}
</style>
